<template>
 <div class="header">
    <div class="left">
       <p>用户管理</p>
       </div>
       <div class="right">
       <el-button type="Search" @click="openAddDialog" plain>添加用户</el-button>
       </div>
 </div>
 <div class="content">
  <el-table :data="paginatedData">
    <el-table-column label="ID" prop="id" ></el-table-column>
    <el-table-column label="用户名" prop="username"></el-table-column>
    <el-table-column label="手机号" prop="phone"></el-table-column>
    <el-table-column label="用户" prop="role"></el-table-column>
    <el-table-column label="操作" >
      <template v-slot="scope">
        <el-button type="primary"  plain @click="openEditDialog(scope.row)">编辑</el-button>
        <el-button type="danger"  plain @click="deleteUser(scope.row)">删除</el-button>
        <el-button type="success" plain @click="openViewDialog(scope.row)">查看</el-button>
      </template>
    </el-table-column>
    
  </el-table>
 
 </div>
 
<!-- 自定义分页控件 -->
<div style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
  <el-button @click="currentPage--" :disabled="currentPage === 1" type="primary" plain>上一页</el-button>

  <span style="margin: 0 10px;">第 {{ currentPage }} 页</span>

  <el-button @click="currentPage++" :disabled="isNextDisabled" type="primary" plain>下一页</el-button>

</div>
  <el-dialog v-model="dialogVisible" title="添加用户" width="40%">
    <el-form ref="formRef" :model="formData" label-width="100px">
      <el-form-item label="用户名">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="formData.phone" />
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="formData.role" placeholder="请选择角色" style="width: 100%">
          <el-option label="用户" value="用户"></el-option>
          <el-option label="服务人员" value="服务人员"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">添加</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog 
    v-model="editorDialogVisible" 
    :title="isEditMode ? '编辑用户' : '用户详情'" 
    width="40%"
  >
    <el-form 
      ref="editFormRef" 
      :model="currentUserData" 
      label-width="100px"
      :disabled="!isEditMode"
    >
      <el-form-item label="用户名">
        <el-input v-model="currentUserData.username" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="currentUserData.phone" />
      </el-form-item>
      <el-form-item label="角色">
        <el-select 
          v-model="currentUserData.role" 
          placeholder="请选择角色" 
          style="width: 100%"
        >
          <el-option label="用户" value="用户"></el-option>
          <el-option label="服务人员" value="服务人员"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeEditorDialog">关闭</el-button>
        <el-button 
          v-if="isEditMode" 
          type="primary" 
          @click="saveUserData"
        >
          保存
        </el-button>
        <el-button 
          v-else 
          type="primary" 
          @click="enableEditMode"
        >
          编辑
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref,onMounted,computed  } from 'vue'
import axios from 'axios'
import { ElMessage,ElMessageBox } from 'element-plus'

let tableData=ref([])
let isEaditing=ref([])
const dialogVisible = ref(false)
const editorDialogVisible = ref(false)
let isEditMode=ref(false)


// 分页相关变量
const currentPage = ref(1)
const pageSize = 3 // 每页显示的数据条数


const isNextDisabled = ref(false)


const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  const pageData = tableData.value.slice(start, end)
  console.log("当前页面数据的长度",tableData.value.slice(start, end).length)
  if(pageData.length <pageSize){
    
    console.log("执行了此方法")
     isNextDisabled.value = true
  }else{
    isNextDisabled.value = false
  }
  // console.log('分页数据:', tableData.value.slice(start, end))
  return tableData.value.slice(start, end)
  
})

// 总页数
const totalPages = computed(() => Math.ceil(tableData.value.length / pageSize))
// 表单引用（用于验证）
const editFormRef = ref(null)
onMounted(()=>{
   fetchUser()
})
const formData = ref({
  username: '',
  phone: '',
  role: '用户'
})
const currentUserData = ref({
  id: null,
  username: '',
  phone: '',
  role: ''
})
const openAddDialog = () => {
  // 重置表单
  formData.value = {
    username: '',
    phone: '',
    role: '用户'
  }
  dialogVisible.value = true
}
let fetchUser= async ()=>{
    try{
        let res =await axios.get('http://localhost:3000/users')
        tableData.value=res.data
         console.log('加载数据:', tableData.value.length)
    } catch (error){
        console.log(error)
    }
}

// 提交表单
const submitForm = async () => {
  try {
    const res = await axios.post('http://localhost:3000/users', formData.value)
    tableData.value.push(res.data)
    dialogVisible.value = false
    ElMessage.success('添加成功')
  } catch (error) {
    ElMessage.error('添加失败')
    console.error(error)
  }
}
//编辑表单
// 打开编辑弹窗
const openEditDialog = (user) => {
  currentUserData.value = { ...user } // 复制用户数据
  isEditMode.value = true
  editorDialogVisible.value = true
}

// 打开查看弹窗
const openViewDialog = (user) => {
  currentUserData.value = { ...user } // 复制用户数据
  isEditMode.value = false
  editorDialogVisible.value = true
}

// 关闭编辑弹窗
const closeEditorDialog = () => {
  editorDialogVisible.value = false
  isEditMode.value = false
}

// 启用编辑模式
const enableEditMode = () => {
  isEditMode.value = true
}

// 保存用户数据
const saveUserData = async () => {
  try {
    // 表单验证
    if (!currentUserData.value.username) {
      ElMessage.warning('请输入用户名')
      return
    }
    
    if (!currentUserData.value.phone) {
      ElMessage.warning('请输入手机号')
      return
    }
    
    // 发送更新请求
    await axios.put(
      `http://localhost:3000/users/${currentUserData.value.id}`,
      currentUserData.value
    )
    
    // 更新本地数据
    const index = tableData.value.findIndex(
      item => item.id === currentUserData.value.id
    )
    if (index !== -1) {
      tableData.value[index] = { ...currentUserData.value }
    }
    
    ElMessage.success('更新成功')
    closeEditorDialog()
    fetchUser() // 刷新列表
  } catch (error) {
    console.error(error)
    ElMessage.error('更新失败')
  }
}
const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.delete(`http://localhost:3000/users/${user.id}`)
    tableData.value = tableData.value.filter(item => item.id !== user.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

  

</script>

<style scoped lang="scss">
.header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left{  
        p{
            font-size: 25px;
            font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
            
        }
    }
}
.content{
    display: flex;
    justify-content: space-between;
}


</style>
